import io
import os

from random import randint
from PIL import Image
from qiniu import Auth, put_file, etag, BucketManager, build_batch_rename
import qiniu.config

# 需要填写你的 Access Key 和 Secret Key
from qiniu.services.storage import bucket

access_key = 'qYmnE7bShs9orOO7OJyDBB9Dr-4U6o3TaWO0TkEX'
secret_key = 'PTM4JX2SUAKcXNIHdPQYI-UU_Icot3cMkFAp93wa'
q = Auth(access_key, secret_key)
bucket_name = 'python-blog'


def my_upload(img_list):
    # img_url = {}
    img_url = []
    # print('img_list',len(img_list))
    if len(img_url) <= 9:
        for img in img_list:
            _img = img.read()
            size = len(_img) / (1024 * 1024)  # 上传图片的大小 M单位
            image = Image.open(io.BytesIO(_img))
            key = 'imgs'+str(randint(1, 100000))
            name = key+'.{0}'.format(image.format)  # 获取图片后缀（图片格式）
            if size > 1:
                # 压缩
                x, y = image.size
                im = image.resize((int(x / 1.73), int(y / 1.73)), Image.ANTIALIAS)  # 等比例压缩 1.73 倍
            else:
                # 不压缩
                im = image
            im.save(name)
            path = name
            token = q.upload_token(bucket_name, key, 3600)
            qiniu.put_file(token, key, path)
            url = 'http://qiniu.tfyhyc.cn/{}'.format(key)
            # img_url[img.name] = url
            img_url.append(url)
            os.remove(os.path.join(name))
        if img_url is None:
            raise Exception('图片上传有误，请稍后再试')
        return img_url
    raise Exception('最多添加九张图片哦')




